<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Healio - 多Agent聊天系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            height: 100vh;
            overflow: hidden;
        }

        .container {
            display: flex;
            height: 100vh;
        }

        /* 左侧聊天列表 */
        .sidebar {
            width: 300px;
            background: #2c3e50;
            color: white;
            transition: width 0.3s ease;
            display: flex;
            flex-direction: column;
        }

        .sidebar.collapsed {
            width: 60px;
        }

        .sidebar-header {
            padding: 20px;
            background: #34495e;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .sidebar.collapsed .sidebar-header {
            padding: 20px 15px;
        }

        .sidebar-title {
            font-size: 18px;
            font-weight: 600;
        }

        .sidebar.collapsed .sidebar-title {
            display: none;
        }

        .toggle-btn {
            background: none;
            border: none;
            color: white;
            font-size: 18px;
            cursor: pointer;
            padding: 5px;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        .toggle-btn:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .new-chat-btn {
            background: #3498db;
            border: none;
            color: white;
            padding: 12px 20px;
            margin: 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .sidebar.collapsed .new-chat-btn {
            margin: 20px 10px;
            padding: 12px;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .new-chat-btn:hover {
            background: #2980b9;
        }

        .chat-list {
            flex: 1;
            overflow-y: auto;
            padding: 0 20px;
        }

        .sidebar.collapsed .chat-list {
            padding: 0 10px;
        }

        .chat-item {
            padding: 15px 10px;
            cursor: pointer;
            border-radius: 8px;
            margin-bottom: 8px;
            transition: background-color 0.3s;
            border-left: 3px solid transparent;
        }

        .chat-item:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .chat-item.active {
            background: rgba(52, 152, 219, 0.3);
            border-left-color: #3498db;
        }

        .chat-item-title {
            font-weight: 500;
            margin-bottom: 4px;
        }

        .chat-item-preview {
            font-size: 12px;
            color: #bdc3c7;
            opacity: 0.8;
        }

        .sidebar.collapsed .chat-item-title,
        .sidebar.collapsed .chat-item-preview {
            display: none;
        }

        .sidebar.collapsed .chat-item {
            text-align: center;
            padding: 15px 5px;
        }

        /* 右侧聊天界面 */
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: white;
        }

        .chat-header {
            padding: 20px 30px;
            background: white;
            border-bottom: 1px solid #ecf0f1;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .chat-title {
            font-size: 20px;
            font-weight: 600;
            color: #2c3e50;
        }

        .agent-selector {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .agent-btn {
            background: #ecf0f1;
            border: none;
            padding: 8px 16px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            color: #2c3e50;
        }

        .agent-btn.active {
            background: #3498db;
            color: white;
        }

        .agent-btn:hover {
            transform: translateY(-1px);
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px 30px;
            background: #f8f9fa;
        }

        .message {
            display: flex;
            margin-bottom: 20px;
            align-items: flex-end;
        }

        .message.user {
            justify-content: flex-end;
        }

        .message-bubble {
            max-width: 60%;
            padding: 12px 18px;
            border-radius: 18px;
            font-size: 14px;
            line-height: 1.4;
            position: relative;
        }

        .message.user .message-bubble {
            background: #3498db;
            color: white;
            border-bottom-right-radius: 4px;
        }

        .message:not(.user) .message-bubble {
            background: white;
            color: #2c3e50;
            border: 1px solid #ecf0f1;
            border-bottom-left-radius: 4px;
        }

        .message-info {
            display: flex;
            align-items: center;
            margin-bottom: 4px;
            font-size: 12px;
            gap: 8px;
        }

        .message.user .message-info {
            justify-content: flex-end;
        }

        .message-sender {
            font-weight: 600;
            color: #7f8c8d;
        }

        .message-time {
            color: #95a5a6;
        }

        .message-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin: 0 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: 600;
            color: white;
        }

        .message.user .message-avatar {
            background: #3498db;
            order: 2;
        }

        .message:not(.user) .message-avatar {
            background: #e74c3c;
        }

        .chat-input {
            padding: 20px 30px;
            background: white;
            border-top: 1px solid #ecf0f1;
        }

        .input-container {
            display: flex;
            gap: 12px;
            align-items: flex-end;
        }

        .message-input {
            flex: 1;
            padding: 12px 18px;
            border: 2px solid #ecf0f1;
            border-radius: 25px;
            font-size: 14px;
            resize: none;
            outline: none;
            transition: border-color 0.3s;
            min-height: 44px;
            max-height: 120px;
        }

        .message-input:focus {
            border-color: #3498db;
        }

        .send-btn {
            background: #3498db;
            border: none;
            color: white;
            padding: 12px 20px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            min-width: 80px;
        }

        .send-btn:hover:not(:disabled) {
            background: #2980b9;
            transform: translateY(-1px);
        }

        .send-btn:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
        }

        .loading {
            display: none;
            align-items: center;
            gap: 8px;
            padding: 20px;
            color: #7f8c8d;
            font-style: italic;
        }

        .loading.show {
            display: flex;
        }

        .loading-dots {
            display: flex;
            gap: 4px;
        }

        .loading-dot {
            width: 6px;
            height: 6px;
            background: #3498db;
            border-radius: 50%;
            animation: loading 1.4s infinite ease-in-out;
        }

        .loading-dot:nth-child(1) { animation-delay: -0.32s; }
        .loading-dot:nth-child(2) { animation-delay: -0.16s; }
        .loading-dot:nth-child(3) { animation-delay: 0s; }

        @keyframes loading {
            0%, 80%, 100% {
                transform: scale(0.8);
                opacity: 0.5;
            }
            40% {
                transform: scale(1);
                opacity: 1;
            }
        }

        .welcome-message {
            text-align: center;
            padding: 60px 40px;
            color: #7f8c8d;
        }

        .welcome-message h2 {
            margin-bottom: 10px;
            color: #2c3e50;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: absolute;
                z-index: 1000;
                transform: translateX(-100%);
            }

            .sidebar.show {
                transform: translateX(0);
            }

            .chat-messages {
                padding: 15px 20px;
            }

            .chat-input {
                padding: 15px 20px;
            }

            .message-bubble {
                max-width: 80%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧聊天列表 -->
        <div class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <div class="sidebar-title">聊天记录</div>
                <button class="toggle-btn" onclick="toggleSidebar()">☰</button>
            </div>
            
            <button class="new-chat-btn" onclick="createNewChat()">
                <span class="btn-text">+ 新建对话</span>
                <span class="btn-icon" style="display: none;">+</span>
            </button>
            
            <div class="chat-list" id="chatList">
                <!-- 聊天列表将动态生成 -->
            </div>
        </div>

        <!-- 右侧聊天界面 -->
        <div class="chat-container">
            <div class="chat-header">
                <div class="chat-title" id="chatTitle">选择一个对话开始聊天</div>
                <div class="agent-selector">
                    <span style="margin-right: 10px; color: #7f8c8d;">发送给:</span>
                    <button class="agent-btn active" data-agent="Bob" onclick="selectAgent(this)">Bob</button>
                    <button class="agent-btn" data-agent="Alice" onclick="selectAgent(this)">Alice</button>
                    <button class="agent-btn" data-agent="John" onclick="selectAgent(this)">John</button>
                </div>
            </div>
            
            <div class="chat-messages" id="chatMessages">
                <div class="welcome-message">
                    <h2>欢迎使用 Healio 多Agent聊天系统</h2>
                    <p>选择左侧的对话或创建新对话开始聊天</p>
                </div>
            </div>
            
            <div class="loading" id="loading">
                <span>AI正在思考中</span>
                <div class="loading-dots">
                    <div class="loading-dot"></div>
                    <div class="loading-dot"></div>
                    <div class="loading-dot"></div>
                </div>
            </div>
            
            <div class="chat-input">
                <div class="input-container">
                    <textarea 
                        class="message-input" 
                        id="messageInput" 
                        placeholder="输入消息..." 
                        rows="1"
                        onkeydown="handleKeyDown(event)"
                        oninput="autoResize(this)"
                    ></textarea>
                    <button class="send-btn" id="sendBtn" onclick="sendMessage()">发送</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let chatSessions = new Map();
        let currentSessionId = null;
        let selectedAgent = 'Bob';
        let isProcessing = false;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 创建第一个聊天会话
            createNewChat();
        });

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('collapsed');
            
            // 切换按钮文本显示
            const btnText = sidebar.querySelector('.btn-text');
            const btnIcon = sidebar.querySelector('.btn-icon');
            if (sidebar.classList.contains('collapsed')) {
                btnText.style.display = 'none';
                btnIcon.style.display = 'inline';
            } else {
                btnText.style.display = 'inline';
                btnIcon.style.display = 'none';
            }
        }

        // 创建新聊天
        function createNewChat() {
            const sessionId = generateSessionId();
            const chatSession = {
                id: sessionId,
                title: `对话 ${chatSessions.size + 1}`,
                messages: [],
                lastMessage: '开始新对话...',
                timestamp: new Date()
            };
            
            chatSessions.set(sessionId, chatSession);
            renderChatList();
            switchToChat(sessionId);
        }

        // 生成会话ID
        function generateSessionId() {
            return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        // 渲染聊天列表
        function renderChatList() {
            const chatList = document.getElementById('chatList');
            chatList.innerHTML = '';
            
            chatSessions.forEach((session, sessionId) => {
                const chatItem = document.createElement('div');
                chatItem.className = `chat-item ${sessionId === currentSessionId ? 'active' : ''}`;
                chatItem.onclick = () => switchToChat(sessionId);
                
                chatItem.innerHTML = `
                    <div class="chat-item-title">${session.title}</div>
                    <div class="chat-item-preview">${session.lastMessage}</div>
                `;
                
                chatList.appendChild(chatItem);
            });
        }

        // 切换到指定聊天
        function switchToChat(sessionId) {
            currentSessionId = sessionId;
            const session = chatSessions.get(sessionId);
            
            document.getElementById('chatTitle').textContent = session.title;
            renderMessages();
            renderChatList(); // 更新活跃状态
        }

        // 渲染消息
        function renderMessages() {
            const chatMessages = document.getElementById('chatMessages');
            const session = chatSessions.get(currentSessionId);
            
            if (!session || session.messages.length === 0) {
                chatMessages.innerHTML = `
                    <div class="welcome-message">
                        <h2>开始新对话</h2>
                        <p>选择一个Agent并发送消息开始对话</p>
                    </div>
                `;
                return;
            }
            
            chatMessages.innerHTML = '';
            
            session.messages.forEach(message => {
                const messageElement = createMessageElement(message);
                chatMessages.appendChild(messageElement);
            });
            
            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 创建消息元素
        function createMessageElement(message) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${message.role === '用户' ? 'user' : ''}`;
            
            const time = new Date().toLocaleTimeString('zh-CN', {
                hour12: false,
                hour: '2-digit',
                minute: '2-digit'
            });
            
            const avatarColor = message.role === '用户' ? '#3498db' : getAgentColor(message.name);
            const avatar = message.role === '用户' ? 'U' : message.name.charAt(0);
            
            messageDiv.innerHTML = `
                <div class="message-avatar" style="background: ${avatarColor}">
                    ${avatar}
                </div>
                <div style="flex: 1;">
                    <div class="message-info">
                        <span class="message-sender">${message.name}</span>
                        <span class="message-time">${time}</span>
                    </div>
                    <div class="message-bubble">
                        ${message.content}
                    </div>
                </div>
            `;
            
            return messageDiv;
        }

        // 获取Agent颜色
        function getAgentColor(agentName) {
            const colors = {
                'Bob': '#e74c3c',
                'Alice': '#9b59b6',
                'John': '#f39c12'
            };
            return colors[agentName] || '#95a5a6';
        }

        // 选择Agent
        function selectAgent(button) {
            document.querySelectorAll('.agent-btn').forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            selectedAgent = button.dataset.agent;
        }

        // 处理键盘事件
        function handleKeyDown(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }

        // 自动调整文本框高度
        function autoResize(textarea) {
            textarea.style.height = 'auto';
            textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
        }

        // 发送消息
        async function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const content = messageInput.value.trim();
            
            if (!content || isProcessing || !currentSessionId) {
                return;
            }
            
            // 创建用户消息
            const userMessage = {
                role: '用户',
                name: 'Jim',
                content: content,
                receiver: selectedAgent
            };
            
            // 添加到当前会话
            const session = chatSessions.get(currentSessionId);
            session.messages.push(userMessage);
            session.lastMessage = content;
            
            // 清空输入框并重新渲染
            messageInput.value = '';
            messageInput.style.height = 'auto';
            renderMessages();
            renderChatList();
            
            // 开始处理对话
            await processConversation(userMessage);
        }

        // 处理对话流程
        async function processConversation(message) {
            isProcessing = true;
            updateUIState(true);
            
            try {
                let currentMessage = message;
                
                while (currentMessage.receiver !== 'Jim') {
                    const response = await callAgentAPI(currentSessionId, currentMessage);
                    
                    if (!response) {
                        throw new Error('没有收到响应');
                    }
                    
                    // 添加响应消息到会话
                    const session = chatSessions.get(currentSessionId);
                    session.messages.push(response);
                    session.lastMessage = `${response.name}: ${response.content.substring(0, 30)}...`;
                    
                    // 更新UI
                    renderMessages();
                    renderChatList();
                    
                    // 如果消息是发给用户的，结束循环
                    if (response.receiver === 'Jim') {
                        break;
                    }
                    
                    // 否则继续发送给下一个agent
                    currentMessage = response;
                    
                    // 添加短暂延迟，提升用户体验
                    await new Promise(resolve => setTimeout(resolve, 500));
                }
            } catch (error) {
                console.error('对话处理错误:', error);
                showError('发送消息失败，请重试');
            } finally {
                isProcessing = false;
                updateUIState(false);
            }
        }

        // 调用后端API
        async function callAgentAPI(sessionId, message) {
            try {
                const formData = new FormData();
                formData.append('sessionId', sessionId);
                formData.append('role', message.role);
                formData.append('name', message.name);
                formData.append('content', message.content);
                formData.append('receiver', message.receiver);
                
                const response = await fetch('/agent/chat', {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                return await response.json();
            } catch (error) {
                console.error('API调用错误:', error);
                throw error;
            }
        }

        // 更新UI状态
        function updateUIState(processing) {
            const sendBtn = document.getElementById('sendBtn');
            const messageInput = document.getElementById('messageInput');
            const loading = document.getElementById('loading');
            
            sendBtn.disabled = processing;
            messageInput.disabled = processing;
            
            if (processing) {
                loading.classList.add('show');
                sendBtn.textContent = '发送中...';
            } else {
                loading.classList.remove('show');
                sendBtn.textContent = '发送';
            }
        }

        // 显示错误信息
        function showError(message) {
            // 创建错误消息
            const errorMessage = {
                role: '系统',
                name: '系统',
                content: `❌ ${message}`,
                receiver: 'Jim'
            };
            
            const session = chatSessions.get(currentSessionId);
            session.messages.push(errorMessage);
            renderMessages();
        }

        // 响应式处理
        function handleResize() {
            if (window.innerWidth <= 768) {
                document.getElementById('sidebar').classList.add('mobile');
            } else {
                document.getElementById('sidebar').classList.remove('mobile');
            }
        }

        window.addEventListener('resize', handleResize);
        handleResize(); // 初始化时调用一次
    </script>
</body>
</html> 